{
 "cells": [
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-25T14:32:46.850174Z",
     "start_time": "2024-04-25T14:32:43.375007Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "from langchain.chat_models.gigachat import GigaChat\n",
    "from langchain.agents import AgentType, initialize_agent, load_tools\n",
    "from dotenv import load_dotenv\n",
    "from langchain import hub\n",
    "from langchain.agents import AgentExecutor, create_react_agent, load_tools\n",
    "\n",
    "import os\n",
    "load_dotenv()\n",
    "giga_api = os.getenv(\"GIGA_API\")\n",
    "# Авторизация в сервисе GigaChat\n",
    "llm = GigaChat(\n",
    "    credentials=giga_api,\n",
    "    verify_ssl_certs=False,\n",
    "    scope='GIGACHAT_API_CORP',\n",
    ")\n",
    "tools = load_tools(['arxiv'])\n",
    "prompt = hub.pull(\"hwchase17/react\")\n",
    "\n",
    "\n",
    "agent = create_react_agent(\n",
    "            llm,\n",
    "            tools,\n",
    "            prompt\n",
    "    )\n",
    "\n",
    "agent1 = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "agent2 = AgentExecutor(agent=agent, tools=tools, verbose=True)\n",
    "result_agent = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ],
   "id": "893e2810e9f24ea6",
   "outputs": [],
   "execution_count": 14
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-25T14:32:47.791556Z",
     "start_time": "2024-04-25T14:32:47.464575Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_community.document_loaders import PyPDFLoader\n",
    "\n",
    "loader = PyPDFLoader('2404.14619v1.pdf')\n",
    "pages = loader.load_and_split()\n",
    "data = ''\n",
    "for page in pages:\n",
    "    data += page.page_content"
   ],
   "id": "645ed94e2aecbc04",
   "outputs": [],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-25T14:32:47.994105Z",
     "start_time": "2024-04-25T14:32:47.989817Z"
    }
   },
   "cell_type": "code",
   "source": [
    "def hypothesis_prompt(my_paper):\n",
    "    return f\"\"\"\n",
    "    Проанализируй статью: {my_paper}\n",
    "    Твоя задача: выдвинуть гипотезу по улучшению статьи.\n",
    "    Используй научные методы. Пиши развернуто и с пояснением свой гипотезы.\n",
    "    Веди конструктивный диалог, если аргумент оппонента действительно хорош, то проанализируй его!\n",
    "    Если ты считаешь, что твой собеседник не прав, то найди информацию с помощью своего инструмента, чтобы отстоять свою точку зрения.\n",
    "    Если вы оба пришли к мысли, что гипотеза твоего собеседника плоха, то выдвинь свою.\n",
    "    \"\"\"\n",
    "    \n",
    "\n",
    "def analyze_hypothesis(my_paper):\n",
    "    return f\"\"\"\n",
    "    Проанализируй статью: {my_paper}\n",
    "    Твоя задача: оценить гипотезу по улучшению статьи, которую выдвинул собеседника.\n",
    "    Используй научные методы. Пиши развернуто и с пояснением почему эта гипотеза может быть хорошей или плохой.\n",
    "    Веди конструктивный диалог, если аргумент оппонента действительно хорош, то проанализируй его!\n",
    "    Если ты считаешь, что твой собеседник не прав, то найди информацию с помощью своего инструмента, чтобы отстоять свою точку зрения.\n",
    "    Если вы оба пришли к мысли, что гипотеза твоего собеседника плоха, то выдвинь свою.\n",
    "    \"\"\"\n",
    "\n",
    "hypo_prompt = hypothesis_prompt(data)\n",
    "analyze_prompt = analyze_hypothesis(data)\n",
    "refery_queston = f\"\"\"Ты рефери в споре о том, хорошая гипотеза или нет.\n",
    "Прочитай диалог и определи, хорошу ли гипотезу по улучшению статьи предложили.\n",
    "Диалог:\n",
    "\"\"\""
   ],
   "id": "bb72221523a42850",
   "outputs": [],
   "execution_count": 16
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-25T14:32:48.568773Z",
     "start_time": "2024-04-25T14:32:48.563540Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import textwrap\n",
    "from langchain.schema import AIMessage, HumanMessage, SystemMessage\n",
    "from langchain.memory import ChatMessageHistory\n",
    "\n",
    "def discuss(max_depth=6):\n",
    "    history = ChatMessageHistory()\n",
    "    b1_message = agent1.invoke(\n",
    "            {\n",
    "                'input': hypo_prompt, 'chat_history': history\n",
    "            }\n",
    "    )\n",
    "\n",
    "    print(f\"\"\"\\033[35mYandex: {textwrap.fill(b1_message['output'], 120)}\\033[0m\"\"\")\n",
    "    history.add_user_message(f\"Гипотеза: {b1_message}\")\n",
    "\n",
    "\n",
    "    b2_message = agent2.invoke(\n",
    "        {\n",
    "            'input': hypo_prompt, 'chat_history': history\n",
    "        }\n",
    "    )\n",
    "    for i in range(max_depth):\n",
    "        \n",
    "\n",
    "        print(f\"\"\"\\033[32mGiga: {textwrap.fill(b2_message, 120)}\\033[0m\"\"\")\n",
    "        dialog_as_text.append(f\"Анализ гипотезы: {b2_message}\")\n",
    "        gypothesis_memory.append(HumanMessage(content=b2_message))\n",
    "        analyze_memory.append(AIMessage(content=b2_message))\n",
    "\n",
    "    result = result_agent(\n",
    "        [HumanMessage(content=refery_queston + \"\\n\".join(dialog_as_text))]\n",
    "    ).content\n",
    "    print(f\"Судья: {textwrap.fill(result, 120)}\")"
   ],
   "id": "529d5ef5833489d6",
   "outputs": [],
   "execution_count": 17
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-04-25T14:32:49.191539Z",
     "start_time": "2024-04-25T14:32:49.153302Z"
    }
   },
   "cell_type": "code",
   "source": "discuss()",
   "id": "fb71d3e6c0ec5c68",
   "outputs": [
    {
     "ename": "IndexError",
     "evalue": "list index out of range",
     "output_type": "error",
     "traceback": [
      "\u001B[1;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[1;31mIndexError\u001B[0m                                Traceback (most recent call last)",
      "Cell \u001B[1;32mIn[18], line 1\u001B[0m\n\u001B[1;32m----> 1\u001B[0m \u001B[43mdiscuss\u001B[49m\u001B[43m(\u001B[49m\u001B[43m)\u001B[49m\n",
      "Cell \u001B[1;32mIn[17], line 10\u001B[0m, in \u001B[0;36mdiscuss\u001B[1;34m(max_depth)\u001B[0m\n\u001B[0;32m      8\u001B[0m analyze_memory \u001B[38;5;241m=\u001B[39m [SystemMessage(content\u001B[38;5;241m=\u001B[39manalyze_prompt)]\n\u001B[0;32m      9\u001B[0m \u001B[38;5;28;01mfor\u001B[39;00m i \u001B[38;5;129;01min\u001B[39;00m \u001B[38;5;28mrange\u001B[39m(max_depth):\n\u001B[1;32m---> 10\u001B[0m     b1_message \u001B[38;5;241m=\u001B[39m \u001B[43magent1\u001B[49m\u001B[43m(\u001B[49m\u001B[43mgypothesis_memory\u001B[49m\u001B[43m)\u001B[49m\u001B[38;5;241m.\u001B[39mcontent\n\u001B[0;32m     12\u001B[0m     \u001B[38;5;28mprint\u001B[39m(\u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\"\"\u001B[39m\u001B[38;5;130;01m\\033\u001B[39;00m\u001B[38;5;124m[35mYandex: \u001B[39m\u001B[38;5;132;01m{\u001B[39;00mtextwrap\u001B[38;5;241m.\u001B[39mfill(b1_message,\u001B[38;5;250m \u001B[39m\u001B[38;5;241m120\u001B[39m)\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;130;01m\\033\u001B[39;00m\u001B[38;5;124m[0m\u001B[39m\u001B[38;5;124m\"\"\"\u001B[39m)\n\u001B[0;32m     13\u001B[0m     dialog_as_text\u001B[38;5;241m.\u001B[39mappend(\u001B[38;5;124mf\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mГипотеза: \u001B[39m\u001B[38;5;132;01m{\u001B[39;00mb1_message\u001B[38;5;132;01m}\u001B[39;00m\u001B[38;5;124m\"\u001B[39m)\n",
      "File \u001B[1;32m~\\PycharmProjects\\deephack\\.venv\\Lib\\site-packages\\langchain_core\\_api\\deprecation.py:145\u001B[0m, in \u001B[0;36mdeprecated.<locals>.deprecate.<locals>.warning_emitting_wrapper\u001B[1;34m(*args, **kwargs)\u001B[0m\n\u001B[0;32m    143\u001B[0m     warned \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;01mTrue\u001B[39;00m\n\u001B[0;32m    144\u001B[0m     emit_warning()\n\u001B[1;32m--> 145\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[43mwrapped\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[43margs\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[38;5;241;43m*\u001B[39;49m\u001B[43mkwargs\u001B[49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\PycharmProjects\\deephack\\.venv\\Lib\\site-packages\\langchain\\chains\\base.py:379\u001B[0m, in \u001B[0;36mChain.__call__\u001B[1;34m(self, inputs, return_only_outputs, callbacks, tags, metadata, run_name, include_run_info)\u001B[0m\n\u001B[0;32m    347\u001B[0m \u001B[38;5;250m\u001B[39m\u001B[38;5;124;03m\"\"\"Execute the chain.\u001B[39;00m\n\u001B[0;32m    348\u001B[0m \n\u001B[0;32m    349\u001B[0m \u001B[38;5;124;03mArgs:\u001B[39;00m\n\u001B[1;32m   (...)\u001B[0m\n\u001B[0;32m    370\u001B[0m \u001B[38;5;124;03m        `Chain.output_keys`.\u001B[39;00m\n\u001B[0;32m    371\u001B[0m \u001B[38;5;124;03m\"\"\"\u001B[39;00m\n\u001B[0;32m    372\u001B[0m config \u001B[38;5;241m=\u001B[39m {\n\u001B[0;32m    373\u001B[0m     \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mcallbacks\u001B[39m\u001B[38;5;124m\"\u001B[39m: callbacks,\n\u001B[0;32m    374\u001B[0m     \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mtags\u001B[39m\u001B[38;5;124m\"\u001B[39m: tags,\n\u001B[0;32m    375\u001B[0m     \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mmetadata\u001B[39m\u001B[38;5;124m\"\u001B[39m: metadata,\n\u001B[0;32m    376\u001B[0m     \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mrun_name\u001B[39m\u001B[38;5;124m\"\u001B[39m: run_name,\n\u001B[0;32m    377\u001B[0m }\n\u001B[1;32m--> 379\u001B[0m \u001B[38;5;28;01mreturn\u001B[39;00m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43minvoke\u001B[49m\u001B[43m(\u001B[49m\n\u001B[0;32m    380\u001B[0m \u001B[43m    \u001B[49m\u001B[43minputs\u001B[49m\u001B[43m,\u001B[49m\n\u001B[0;32m    381\u001B[0m \u001B[43m    \u001B[49m\u001B[43mcast\u001B[49m\u001B[43m(\u001B[49m\u001B[43mRunnableConfig\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43m{\u001B[49m\u001B[43mk\u001B[49m\u001B[43m:\u001B[49m\u001B[43m \u001B[49m\u001B[43mv\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;28;43;01mfor\u001B[39;49;00m\u001B[43m \u001B[49m\u001B[43mk\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mv\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;129;43;01min\u001B[39;49;00m\u001B[43m \u001B[49m\u001B[43mconfig\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mitems\u001B[49m\u001B[43m(\u001B[49m\u001B[43m)\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;28;43;01mif\u001B[39;49;00m\u001B[43m \u001B[49m\u001B[43mv\u001B[49m\u001B[43m \u001B[49m\u001B[38;5;129;43;01mis\u001B[39;49;00m\u001B[43m \u001B[49m\u001B[38;5;129;43;01mnot\u001B[39;49;00m\u001B[43m \u001B[49m\u001B[38;5;28;43;01mNone\u001B[39;49;00m\u001B[43m}\u001B[49m\u001B[43m)\u001B[49m\u001B[43m,\u001B[49m\n\u001B[0;32m    382\u001B[0m \u001B[43m    \u001B[49m\u001B[43mreturn_only_outputs\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43mreturn_only_outputs\u001B[49m\u001B[43m,\u001B[49m\n\u001B[0;32m    383\u001B[0m \u001B[43m    \u001B[49m\u001B[43minclude_run_info\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43minclude_run_info\u001B[49m\u001B[43m,\u001B[49m\n\u001B[0;32m    384\u001B[0m \u001B[43m\u001B[49m\u001B[43m)\u001B[49m\n",
      "File \u001B[1;32m~\\PycharmProjects\\deephack\\.venv\\Lib\\site-packages\\langchain\\chains\\base.py:134\u001B[0m, in \u001B[0;36mChain.invoke\u001B[1;34m(self, input, config, **kwargs)\u001B[0m\n\u001B[0;32m    131\u001B[0m include_run_info \u001B[38;5;241m=\u001B[39m kwargs\u001B[38;5;241m.\u001B[39mget(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124minclude_run_info\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;28;01mFalse\u001B[39;00m)\n\u001B[0;32m    132\u001B[0m return_only_outputs \u001B[38;5;241m=\u001B[39m kwargs\u001B[38;5;241m.\u001B[39mget(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mreturn_only_outputs\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;28;01mFalse\u001B[39;00m)\n\u001B[1;32m--> 134\u001B[0m inputs \u001B[38;5;241m=\u001B[39m \u001B[38;5;28;43mself\u001B[39;49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mprep_inputs\u001B[49m\u001B[43m(\u001B[49m\u001B[38;5;28;43minput\u001B[39;49m\u001B[43m)\u001B[49m\n\u001B[0;32m    135\u001B[0m callback_manager \u001B[38;5;241m=\u001B[39m CallbackManager\u001B[38;5;241m.\u001B[39mconfigure(\n\u001B[0;32m    136\u001B[0m     callbacks,\n\u001B[0;32m    137\u001B[0m     \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mcallbacks,\n\u001B[1;32m   (...)\u001B[0m\n\u001B[0;32m    142\u001B[0m     \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mmetadata,\n\u001B[0;32m    143\u001B[0m )\n\u001B[0;32m    144\u001B[0m new_arg_supported \u001B[38;5;241m=\u001B[39m inspect\u001B[38;5;241m.\u001B[39msignature(\u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39m_call)\u001B[38;5;241m.\u001B[39mparameters\u001B[38;5;241m.\u001B[39mget(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mrun_manager\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n",
      "File \u001B[1;32m~\\PycharmProjects\\deephack\\.venv\\Lib\\site-packages\\langchain\\chains\\base.py:480\u001B[0m, in \u001B[0;36mChain.prep_inputs\u001B[1;34m(self, inputs)\u001B[0m\n\u001B[0;32m    476\u001B[0m     \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mmemory \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[0;32m    477\u001B[0m         \u001B[38;5;66;03m# If there are multiple input keys, but some get set by memory so that\u001B[39;00m\n\u001B[0;32m    478\u001B[0m         \u001B[38;5;66;03m# only one is not set, we can still figure out which key it is.\u001B[39;00m\n\u001B[0;32m    479\u001B[0m         _input_keys \u001B[38;5;241m=\u001B[39m _input_keys\u001B[38;5;241m.\u001B[39mdifference(\u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mmemory\u001B[38;5;241m.\u001B[39mmemory_variables)\n\u001B[1;32m--> 480\u001B[0m     inputs \u001B[38;5;241m=\u001B[39m {\u001B[38;5;28;43mlist\u001B[39;49m\u001B[43m(\u001B[49m\u001B[43m_input_keys\u001B[49m\u001B[43m)\u001B[49m\u001B[43m[\u001B[49m\u001B[38;5;241;43m0\u001B[39;49m\u001B[43m]\u001B[49m: inputs}\n\u001B[0;32m    481\u001B[0m \u001B[38;5;28;01mif\u001B[39;00m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mmemory \u001B[38;5;129;01mis\u001B[39;00m \u001B[38;5;129;01mnot\u001B[39;00m \u001B[38;5;28;01mNone\u001B[39;00m:\n\u001B[0;32m    482\u001B[0m     external_context \u001B[38;5;241m=\u001B[39m \u001B[38;5;28mself\u001B[39m\u001B[38;5;241m.\u001B[39mmemory\u001B[38;5;241m.\u001B[39mload_memory_variables(inputs)\n",
      "\u001B[1;31mIndexError\u001B[0m: list index out of range"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "76d68c625c6e063a"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
